import React, { PureComponent } from 'react';
import { connect } from 'dva';

import { Row, Col, Icon, Form, Button, Checkbox, Avatar, AutoComplete, Popconfirm, Modal, Select, Input, Radio } from 'antd';
import styles from './styles.less';

const CheckboxGroup = Checkbox.Group;
const FormItem = Form.Item;
const AutoCompleteOption = AutoComplete.Option;
const RadioGroup = Radio.Group;
const { TextArea } = Input;



const ModelName = "inv";
@connect(({ loading, relationer, mbl }) => ({
  loading: loading.models[ModelName],
  relationers: relationer.list,
  mbl: mbl.current,
}))
@Form.create()
class Comp extends PureComponent {

  state = {
    relListbySearch: [],
    relId: 0,
  }

  constructor(props) {
    super(props);
    this.state = {
      relList: [],
      invType: 1,
      selectedRel: undefined,
    };

    const { getInstance } = props;
    if (typeof getInstance === 'function') {
      getInstance(this);
    }
  }

  componentDidMount() {
    const { dispatch, mbl } = this.props;
    dispatch({
      type: 'relationer/getShippersByBillId',
      payload: mbl.id,
      callback: resp => {
        this.setState({ relList: resp });
      }
    })
  }

  handleInvTypeChange = (e) => {
    const { dispatch, mbl, relationers } = this.props;
    const invType = e.target.value;
    console.log(e.target.value);
    this.setState({ invType: e.target }, () => {
      if (invType === 1) {  // 工厂账单: 分单发货人
        dispatch({
          type: 'relationer/getShippersByBillId',
          payload: mbl.id,
          callback: resp => {
            this.setState({ relList: resp });
          }
        })
      } else if (invType === 2) {  // 客户账单: 主单收货人
        this.setState({ relList: relationers.filter(r => r.id === mbl.consigneeId) });
      } else if (invType === 3) { // 供应商账单: 自定义
        this.setState({ relList: [] });
      }
    });
  }

  handleRelSelected(value) {
    const { relationers } = this.props;
    const selectRel = relationers.find(r => r.id === Number(value));
    this.setState({ selectedRel: selectRel });
  }

  handleSubmit(e) {
    e.preventDefault();
    const { form } = this.props;
    form.validateFields((err, values) => {
      if (err) {
        return;
      }

      const vm = {
        ...values,
        selectedRel: this.state.selectedRel
      };
      console.log("VM TO INV:", vm);
      this.props.onOk(vm)
    });

  }

  render() {
    const { form: { getFieldDecorator }, relationers } = this.props;
    const { relList, selectedRel } = this.state;
    const { visible, onCancel } = this.props;

    const formLayout = {
      labelCol: {
        sm: { span: 4 },
      },
      wrapperCol: {
        sm: { span: 14 },
      },
    };

    return (

      <Modal
        title={'添加账单'}
        destroyOnClose
        visible={visible}
        width={900}
        onOk={(e) => this.handleSubmit(e)}
        onCancel={onCancel}
      >
        <Form onSubmit={this.handleSubmit} className={styles.form}>
          <FormItem label="账单类型" {...formLayout}>
            {getFieldDecorator('invoiceType', {
              rules: [{ required: true }],
              initialValue: 1,
            })(
              <RadioGroup onChange={(e) => this.handleInvTypeChange(e)}>
                {[{ id: 1, objectName: '工厂账单' }, { id: 2, objectName: '客户账单' }, { id: 3, objectName: '供应商账单' }].map(item => <Radio key={item.id} value={item.id} >{item.objectName}</Radio>)}
              </RadioGroup>
            )}
          </FormItem>
          <FormItem label="单位名称" {...formLayout}>
            {getFieldDecorator('rel')(
              <CheckboxGroup>
                {relList.map(item => <Row><Checkbox key={item.id} value={item.id}>{item.objectName}</Checkbox></Row>)}
              </CheckboxGroup>
            )}
          </FormItem>
          <FormItem label="自定义单位" {...formLayout} >
            {getFieldDecorator('relAddName', {
              initialValue: selectedRel && selectedRel.objectName
            })(
              <AutoComplete
                placeholder="名称"
                autoFocus={true}
                backfill={true}
                onChange={(value) => { this.handleRelSelected(value) }}
                filterOption={(inputValue, option) => option.props.children.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1} >
                {relationers.map((rel) => { return <AutoCompleteOption key={rel.id} value={String(rel.id)} >{rel.objectName}</AutoCompleteOption> })}
              </AutoComplete>
            )}
          </FormItem>
          <FormItem label="自定义单位" {...formLayout} >
            {getFieldDecorator('relAddAddress', {
              initialValue: selectedRel && selectedRel.address
            })(
              <TextArea placeholder="地址" />
            )}
          </FormItem>
        </Form >
      </Modal>
    );
  }
}

export default Comp;

